<template>
	<view class="">
		<cu-custom bgColor="bg-gradual-pink" :isBack="true">
			<block slot="backText">返回</block>
			<block slot="content">设备标签打印</block>
		</cu-custom>

		<view class="padding-sm solids-bottom" :style="{height: listLoading?'20vh':'15vh'}">
			<view class="flex align-center" style="width: 100%;">
				<view class="flex align-center margin-top-sm flex-1">
					<view class="flex align-center flex-1 solid-bottom">
						<text class="text-bold">设备信息</text>
						<view class="margin-left-sm solids padding-xs" style="width: 50%;">
							<input v-model="searchData.keyWord" class="text-grey" placeholder="请输入" />
						</view>
					</view>
				</view>
				<view class="flex align-center margin-top-sm flex-1">
					<view class="flex align-center flex-1 solid-bottom">
						<text class="text-bold">扫码信息</text>
						<view class="margin-left-sm solids padding-xs" style="width: 50%;">
							<input v-model="searchData.equalKeyWord" class="text-grey" placeholder="请输入" />
						</view>
					</view>
					<text style="transform: scale(1.5)" class=' cuIcon-scan text-black' @click="searchSandCode">
					</text>
				</view>
			</view>


			<view class="flex align-center margin-top-sm">

				<view class="flex-1 text-right">
					<button @click="initData(searchData)" class="cu-btn bg-blue">
						搜索
					</button>
					<button @click="restinitData(searchData)" class="cu-btn bg-yellow margin-left-sm">
						重置
					</button>
				</view>
			</view>
			<view v-if="listLoading" class="flex align-center margin-top-sm">
				<view class="flex align-center justify-center flex-1">
					<block>
						<text class="text-bold margin-right-xs">正在加载中</text>
						<image src="../../static/5-121204193R0-50.gif" style="width: 50rpx;height: 50rpx;"></image>
					</block>
				</view>
			</view>
		</view>
		<view class="content-s">
			<kk-printer ref="kkprinter" :bufferData="bufferData" @onPrint="onPrint"></kk-printer>
		</view>
		<scroll-view scroll-y :style="[listLoading?{height:'calc(100vh - ' + CustomBar + 'px  - 30vh)'}
		:{height:'calc(100vh - ' + CustomBar + 'px  - 25vh)'}]" :scroll-top="scrollTop" @scroll="scroll">
			<view v-for="(item,index) in tableData" :key="index">
				<view :data-id="item.repairNo" :data-num='item.nowRepairStep' :data-no="item.equipmentNo"
					style="padding:0 20rpx ;"
					class="bg-grey text-sm shadow-warp full-solids-bottom list_main_item margin-top-sm">
					<view class="flex justify-between align-center">
						<view class="flex-4 ">
							<view class="margin-top-sm text-sm">
								<text class="item-label">工器具名称：</text>
								<text class="">{{item.toolName || '--'}}</text>
							</view>

							<view class="margin-top-sm text-sm">
								<text class="item-label">物资编码：</text>
								<text class="">{{item.materialCode|| '--'}} </text>
							</view>
							<view class="margin-top-sm text-sm">
								<text class="item-label">UTC编码：</text>
								<text class="">{{item.utcCode|| '--'}} </text>
							</view>
							<view class="margin-top-sm text-sm">
								<text class="item-label">出厂编码：</text>
								<text class="">{{item.serialNumber|| '--'}} </text>
							</view>
							<view class="margin-top-sm text-sm" v-if="item.isInspected === '是'">
								<text class="item-label">检验有效期：</text>
								<text class="">{{item.inspectionValidityPeriod|| '--'}} </text>
							</view>
							<view class="margin-top-sm text-sm" v-else>
								<text class="item-label">保养有效期：</text>
								<text class="">{{item.maintenanceValidityPeriod|| '--'}} </text>
							</view>
							<view class="margin-top-sm text-sm">
								<text class="item-label">维修次数：</text>
								<text class="">{{item.repairNum|| '--'}} </text>
							</view>


							<view class=" text-xl text-right text-bold margin-bottom-sm margin-top-sm">
								<button @click="goRepair(item)" class="cu-btn bg-red margin-right-sm">
									维修
									<view class="cu-tag badge" v-if="item.repairStatus !== '正常'">
										<block></block>
									</view>
								</button>
								<button @click="onMain(item)" class="cu-btn bg-green margin-right-sm">
									保养
									<view class="cu-tag badge" v-if="item.maintenanceStatus !== '正常'">
										<block></block>
									</view>
								</button>
								<button @click="goHistory(item)" class="cu-btn bg-blue margin-right-sm">
									履历
								</button>
								<button @click="onPrint2(item)" class="cu-btn bg-purple margin-right-sm">
									打印
								</button>

							</view>
						</view>
					</view>
				</view>
			</view>
		</scroll-view>
		<view class="flex align-center justify-center" style="position: absolute;bottom: 0;height: 10vh;width: 100%;">
			<wyb-pagination :current="pageNum" :page-items="pageSize" :total-items="total" @change="pageChange" />
		</view>


	</view>
</template>

<script>
	import util from '@/components/kk-printer/utils/util.js';
	import * as blesdk from '@/components/kk-printer/utils/bluetoolth.js';
	import kkPrinter from '@/components/kk-printer/index.vue';
	import {
		deepClone,
		isEmpty
	} from "@/common/base";
	import wybPagination from '@/components/wyb-pagination/wyb-pagination.vue'
	export default {
		data() {
			return {
				bufferData: '',
				scrollTop: 0,
				old: {
					scrollTop: 0
				},
				listLoading: false,
				pageNum: 1,
				pageSize: 5,
				total: 0,
				userInfo: this.$helper.userInfo,
				searchData: {
					keyWord: '',
					equalKeyWord: ''
				},
				noOrderSize: 0,
				orderSize: 0,
				equipmentNo: '',
				searchText: '',
				TabCur: 0,
				TabList: ['未接单', '已接单', '2小时未处理', '生产待确认'],
				tableData: [],
				CustomBar: this.CustomBar,
				formInfo: {}
			}
		},
		components: {
			kkPrinter,
			wybPagination
		},
		onShow(obj) {
			this.initData()
		},
		onLoad(obj) {
			// 判断如果填写完成表格跳转过来, 则定位到具体数据
			if (obj.materialCode && obj.serialNumber) {
				this.searchData.equalKeyWord = obj.materialCode + ',' + obj.serialNumber
				setTimeout(() => {
					this.initData(this.searchData)
				}, 200)
			}
		},
		methods: {
			goRepair(row) {
				if (row.repairStatus === '正常') {
					uni.navigateTo({
						url: '/pages/index/index?materialCode=' + row.materialCode + '&serialNumber=' + row
							.serialNumber
					})
				}
				if (row.repairStatus === '维修中') {
					uni.navigateTo({
						url: '/pages/index/index?materialCode=' + row.materialCode + '&serialNumber=' + row
							.serialNumber + '&status=0'
					})
				}

			},
			onMain(row) {
				if (row.maintenanceStatus === '正常') {
					uni.navigateTo({
						url: '/pages/main/index?materialCode=' + row.materialCode + '&serialNumber=' + row
							.serialNumber
					})
				}
				if (['保养中', '检验中'].includes(row.maintenanceStatus)) {
					uni.navigateTo({
						url: '/pages/main/index?materialCode=' + row.materialCode + '&serialNumber=' + row
							.serialNumber + '&status=0'
					})
				}

			},
			goHistory(row) {
				uni.navigateTo({
					url: '/pages/equipment-history/index?materialCode=' + row.materialCode + '&serialNumber=' + row
						.serialNumber
				})
			},

			initData(aa) {
				var that = this;
				const params = deepClone(aa) || {}
				params.pageNum = that.pageNum
				params.pageSize = that.pageSize
				params.isEnable = '1'
				that.listLoading = true;
				that.$api.postAPI('/tpm/api/device/list', params).then(res => {
					if (res.code == 0) {
						let resData = res.data.rows;
						that.tableData = resData;
						that.total = res.data.total;
						that.goTop();
					} else {
						that.tableData = [];
						that.total = 0;
						uni.showToast({
							title: res.message,
							icon: 'none',
							duration: 3000
						});
					}
					that.listLoading = false;
				}).catch(error => {
					that.tableData = [];
					that.total = 0;
					that.listLoading = false;
					uni.showToast({
						title: '服务器异常:' + JSON.stringify(error),
						icon: 'none',
						duration: 3000
					});
				})
			},
			getDate0(str) {
				if (isEmpty(str)) return
				return str.split(' ')[0]
			},
			onPrint2(row) {
				this.formInfo = deepClone(row)
				if (this.$refs.kkprinter) this.$refs.kkprinter.handlePrintTap()
			},
			onPrint(opt) {
				let that = this
				// 页面尺寸：40mm x 30mm（假设打印机DPI为203，1mm ≈ 8点）
				const width = 50 * 8; // 40mm -> 320点
				const height = 40 * 8; // 30mm -> 240点
				// 创建CPCL页面
				let strCmd = blesdk.CreatCPCLPage(width, height, 1, 0);
				// 随机生成设备信息
				const deviceNo = this.formInfo.materialCode

				const date = this.formInfo.isInspected === '是' ? that.getDate0(this.formInfo.inspectionValidityPeriod) :
					that.getDate0(this.formInfo.maintenanceValidityPeriod)
				const str = this.formInfo.isInspected === '是' ? '检验有效期' : '保养有效期'
				const qrContent = this.formInfo.materialCode + ',' + this.formInfo.serialNumber
				// 添加设备编号
				strCmd += blesdk.addCPCLText(0, 30, '24', '0', 0, `物资编码: ${deviceNo}`);

				// 添加有效日期
				strCmd += blesdk.addCPCLText(0, 60, '24', '0', 0, `${str}: ${date}`);

				// 添加设备编号
				strCmd += blesdk.addCPCLText(0, 90, '24', '0', 0, '检定单位: 上海霁青机械');

				// 添加二维码
				strCmd += blesdk.addCPCLQRCode(100, 130, 'M', 2, 4, qrContent);
				// 添加打印命令
				strCmd += blesdk.addCPCLPrint();
				// 打印调试信息
				console.log(strCmd, '生成的CPCL命令');
				// 存储生成的命令字符串
				this.bufferData = strCmd;
			},

			hideModal() {
				this.modalName = null
			},
			scroll: function(e) {
				this.old.scrollTop = e.detail.scrollTop
			},
			goTop: function(e) {
				this.scrollTop = this.old.scrollTop
				this.$nextTick(() => {
					this.scrollTop = 0
				});
			},
			pageChange(e) {
				var that = this;
				console.log(e);
				that.pageNum = e.current;
				that.initData(that.searchData);
			},
			bindDateChange(e) {
				var that = this;
				let operTime = [];
				let value = e.detail.value;
				let type = e.currentTarget.dataset.type;
				that.searchData[type] = value;
				that.$forceUpdate();
			},
			restinitData() {
				var that = this;
				that.pageNum = 1;
				that.pageSize = 20;
				that.searchData = {
					keyWord: '',
				};
				that.initData();
			},
			searchSandCode() {
				let that = this
				uni.scanCode({
					onlyFromCamera: true,
					success: function(res) {
						that.searchData.equalKeyWord = res.result.replace(/\n/g, '');
					}
				});
			}

			// TPMcodeScan() {
			// 	var that = this;
			// 	uni.scanCode({
			// 		onlyFromCamera: true,
			// 		success: function(res) {
			// 			console.log("scanCode:", res);
			// 			that.equipmentNo = res.result;
			// 			that.$helper.equipmentNo = that.equipmentNo;
			// 			uni.navigateTo({
			// 				url: '../index/index'
			// 			});
			// 		}
			// 	});
			// },

		}
	}
</script>

<style>
	.search-input {
		margin-left: 30upx;
		border: 2upx solid #333333;
		width: 70%;
		border-radius: 25upx;
		padding: 10upx;
		font-size: 24rpx;
	}

	.list_main_item {
		width: 720rpx;
	}

	.list_main_item {
		width: 720rpx;
		border-top-right-radius: 50rpx;
		border-bottom-right-radius: 50rpx;
	}

	.big-type-line {
		width: 185rpx;
		height: 8rpx;
		border-radius: 15rpx;
	}

	.content-s {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	}

	.btn-wrap {
		width: 180upx;
		height: 100upx;
		border-radius: 16upx;
		border: 2upx solid #333333;
		box-sizing: border-box;
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.item-label {
		font-weight: bold;
	}

	.bgCor1 {
		background-color: #FF4500;
	}

	.bgCor2 {
		background-color: #34C759;
	}

	.bgCor3 {
		background-color: #007AFF;
	}

	.bgCor4 {
		background-color: #623CEA;
	}
</style>